import { Injectable } from '@nestjs/common';
import { Request } from 'express';
import { LoginDto } from './dto/auth.dto';
import { CustomException, ErrorCode } from 'src/common/exceptions/custom.exception';
import { User } from '../user/entities/user.entity';
import { JwtCustomPayload } from 'src/types';
import { JwtConfigService } from '../jwt/jwt.config.service';
import { CaptchaService } from '../captcha/captcha.service';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtConfigService: JwtConfigService,
    private readonly captchaService: CaptchaService,
    private readonly redisService: RedisService,
  ) {}

  /** 生成验证码 */
  async createCaptcha() {
    return await this.captchaService.genCaptcha();
  }

  /** 登录 */
  async login(req: Request, body: LoginDto) {
    // 验证校验码
    if (!this.captchaService.validateCaptcha(6, body.captcha)) {
      throw new CustomException(ErrorCode.ERR_10003);
    }
    // 验证用户是否有enable为true的角色
    const user = req.user as User;
    if (!user.roles.some((item) => item.enable)) {
      throw new CustomException(ErrorCode.ERR_11003);
    }
    const roleCodes = user.roles.map((item) => item.code);
    const currentRole = user.roles[0];
    const payload: JwtCustomPayload = {
      userId: user.id,
      username: user.username,
      roleCodes,
      currentRoleCode: currentRole.code,
    };
    const accessToken = await this.jwtConfigService.generateToken(payload);
    return { accessToken, userId: user.id };
  }

  /** 退出登录 */
  logout(req: Request) {
    console.log(req, '===>>>');
    const reqUser = req.user as JwtCustomPayload;
    const tokenKey = this.jwtConfigService.getAccessTokenKey(reqUser.userId);
    const token = this.redisService.getString(tokenKey);
    if (token) {
      this.redisService.delString(tokenKey);
    }

    return null;
  }
}
